package com.xtayfjpk.security;

import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Arrays;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;

public class MyAliasedX509ExtendKeyManager extends X509ExtendedKeyManager {
	private String keyAlias;
    private X509KeyManager keyManager;
    
    public MyAliasedX509ExtendKeyManager(String keyAlias, X509KeyManager keyManager) {
    	this.keyAlias = keyAlias;
    	this.keyManager = keyManager;
    }
	

    //提供给客户端使用，用于选择客户端Keystore中的一个别名
	@Override
	public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
		System.out.println(Arrays.asList(keyTypes));
		System.out.println(Arrays.asList(issuers));
		String alias = keyAlias==null ? keyManager.chooseClientAlias(keyTypes, issuers, socket) : keyAlias;
		System.out.println("chooseClientAlias invoked, alias=" + alias);
		return alias;
	}

	//提供给服务端使用，用于选择服务端Keystore中的一个别名
	@Override
	public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
		String alias =  keyAlias==null ? keyManager.chooseServerAlias(keyType, issuers, socket) : keyAlias;
		System.out.println("chooseServerAlias invoked, alias=" + alias);
		return alias;
	}

	@Override
	public X509Certificate[] getCertificateChain(String alias) {
		return keyManager.getCertificateChain(alias);
	}

	@Override
	public String[] getClientAliases(String keyType, Principal[] issuers) {
		return keyManager.getClientAliases(keyType, issuers);
	}

	@Override
	public PrivateKey getPrivateKey(String alias) {
		return keyManager.getPrivateKey(alias);
	}

	@Override
	public String[] getServerAliases(String keyType, Principal[] issuers) {
		return keyManager.getServerAliases(keyType, issuers);
	}

	@Override
	public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
		String alias =  keyAlias==null ? super.chooseEngineClientAlias(keyType, issuers, engine) : keyAlias;
		System.out.println("chooseEngineClientAlias invoked, alias=" + alias);
		return alias;
	}
	
	@Override
	public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
		String alias =  keyAlias==null ? super.chooseEngineServerAlias(keyType, issuers, engine) : keyAlias;
		System.out.println("chooseEngineServerAlias invoked, alias=" + alias);
		return alias;
	}
}
